#!/usr/bin/env python2

import os

from utils import Exp, _dmsg, _dwarn, _derror, _human_readable, _human_unreadable, _exec_pipe1, _exec_system, \
        _str2dict, _syserror, _syswarn, _lock_file1, _unlock_file1, _file_read
from disk.Iface import DISK_Iface


# struct ext4_super_block offset = 1024; ext4_super_block.s_reserved offset = 588;
VALID_DATA_OFFSET = 1024 + 588
# sizeof(ext4_super_block.s_reserved) = 109
VALID_DATA_LEN = 109 + 1024
DISK_INFO_OFFSET = 4096
FILE_BLOCK_LEN = 4096

class File(DISK_Iface):
    def get_disk_pool(self, dev):
        buf = _file_read(dev, VALID_DATA_OFFSET, VALID_DATA_LEN)
        d = _str2dict(buf, ';', '=')
        return d['pool']

    def disk_load_valid(self, dev, clusteruuid, hostname):
        buf = _file_read(dev, VALID_DATA_OFFSET, VALID_DATA_LEN)
        d = _str2dict(buf, ';', '=')
        if 'cluster' in d and 'node' in d:
            if d['cluster'] == clusteruuid and d['node'] == hostname:
                return d

    def disk_info_valid(self, dev, buff):
        valid = _file_read(dev, DISK_INFO_OFFSET, len(buff))
        return valid == buff

    def disk_read(self, dev, offset, size):
        return _file_read(dev, offset, size)

    def disk_write(self, dev, buff, offset):
        return _file_write(dev, buff, offset)

    def get_disk_info(self, dev):
        return  {'type':'File', 'size':_human_readable(os.path.getsize(dev))}

    def show_disk_info(self, dev, dev_info):
        return "%s %s %s" % (dev, dev_info['type'], dev_info['size'])

    def disk_add_superblock(self, dev, disk_num, pool, cache, clusteruuid, hostname):
        data = 'cluster=%s;node=%s;type=new;disk=%s;pool=%s;cache=%s;cached=0;\0' % (clusteruuid, hostname, disk_num, pool, cache)
        _file_write(dev, data, VALID_DATA_OFFSET)

    def disk_del_superblock(self, dev):
        buff = '\0' * FILE_BLOCK_LEN
        _file_write(dev, buff)
